package com.rocksea.app.fragment;

import android.content.Context;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.PopupMenu;
import android.support.v7.widget.RecyclerView;
import android.util.SparseBooleanArray;
import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.CheckBox;
import android.widget.TextView;

import com.rocksea.app.BaseFragment;
import com.rocksea.app.R;
import com.rocksea.app.activity.BaseShowActivity;
import com.rocksea.app.db.DbCenter;
import com.rocksea.app.db.lowStrain.LowStrainDb;
import com.rocksea.app.utils.UiUtils;
import com.rocksea.app.weight.DividerListItemDecoration;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.InjectView;
import butterknife.OnClick;


/**
 * Created by Mrw on 2017/11/13.
 *
 */

public class LowStrainDataFragment extends BaseFragment
{

    @InjectView(R.id.Wave_Data)
    RecyclerView mRecyclerView;
    @InjectView(R.id.Multiple_layout)
    View multipleLayout;


    private List<LowStrainDb.LowStrainDataDb>  mLowStrainDatas;
    private WaveAdapter waveAdapter;

    public LowStrainDataFragment() {
    }
    public static LowStrainDataFragment newInstance(Bundle bundle) {
        LowStrainDataFragment fragment = new LowStrainDataFragment();
        fragment.setArguments(bundle);
        return fragment;
    }
    @Override
    protected void initView() {
        LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
        mRecyclerView.setLayoutManager(layoutManager);
        mRecyclerView.addItemDecoration(new DividerListItemDecoration(getContext(),DividerListItemDecoration.VERTICAL_LIST));
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
        multipleLayout.setVisibility(View.GONE);

    }


    @Override
    protected void initData() {
        Bundle bundle = getArguments();
        String baseInfoId = bundle.getString(BaseShowActivity.BASEINFOID_KEY);
        QueryWaveTask queryWaveTask = new QueryWaveTask(baseInfoId);
        queryWaveTask.execute();
    }
    @Override
    protected void requestAgain() {

    }
    @Override
    protected int getContentViewId()
    {
        return R.layout.fragment_lowstrain_layout;
    }


    private static class QueryWaveTask extends AsyncTask<Void,Void,List<LowStrainDb.LowStrainDataDb> >
    {
        private String baseInfoId;

        public QueryWaveTask(String baseInfoId)
        {
            this.baseInfoId = baseInfoId;
        }

        @Override
        protected List<LowStrainDb.LowStrainDataDb> doInBackground(Void... params)
        {
            return DbCenter.mDyDbHelper.queryWaveData(baseInfoId,false);

        }
        @Override
        protected void onPostExecute(List<LowStrainDb.LowStrainDataDb>  lowStrainDatas)
        {
            super.onPostExecute(lowStrainDatas);
            EventBus.getDefault().post(lowStrainDatas);
        }

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void refreshList(List<LowStrainDb.LowStrainDataDb>  lowStrainDatas)
    {
        if (lowStrainDatas.size()==0)
        {
            loadFailed();
            mErrorText.setText("未检测到采样数据");
            return;
        }

        if (mLowStrainDatas==null)
        {
            mLowStrainDatas = new ArrayList<>();
            mLowStrainDatas.addAll(lowStrainDatas);
        }
        else
        {
            mLowStrainDatas.clear();
            mLowStrainDatas .addAll(lowStrainDatas);
        }
        waveAdapter = new WaveAdapter(getContext(),lowStrainDatas);
        mRecyclerView.setAdapter(waveAdapter);
    }


    @OnClick(R.id.cancel)
    public void cancel(View view)
    {
        waveAdapter.setIsCheckedMode(false);
        multipleLayout.setVisibility(View.GONE);
    }


    @OnClick(R.id.checkAll)
    public void checkAll(View view)
    {
        waveAdapter.checkedAll();
    }

    @OnClick(R.id.valid)
    public void valid(View view)
    {
        waveAdapter.makeValidFlag(true);
    }

    @OnClick(R.id.unValid)
    public void unValid(View view)
    {

        waveAdapter.makeValidFlag(false);

    }



    private void notifyDataChanged()
    {
        waveAdapter.notifyDataSetChanged();
    }

    private class WaveAdapter extends RecyclerView.Adapter<WaveViewHodler>
    {
        private Context context;
        private List<LowStrainDb.LowStrainDataDb> lowStrainDataDbs;
        private SparseBooleanArray chckeLink = new SparseBooleanArray();
        private boolean checkable = false;

        public WaveAdapter(Context context, List<LowStrainDb.LowStrainDataDb> lowStrainDataDbs)
        {
            this.context = context;
            this.lowStrainDataDbs = lowStrainDataDbs;
            for (int i = 0; i < this.lowStrainDataDbs.size(); i++) {
                chckeLink.put(i,false);
            }

        }
        @Override
        public WaveViewHodler onCreateViewHolder(ViewGroup viewGroup, int i)
        {
            View mBootView = LayoutInflater.from(context).inflate(R.layout.wave_counts_item_layout,viewGroup,false);
            return new WaveViewHodler(mBootView);
        }
        @Override
        public void onBindViewHolder(final WaveViewHodler waveViewHodler, final int i)
        {
            waveViewHodler.tvSerilaNo.setText(String.valueOf(i+1));
            waveViewHodler.tvInfo.setText(String.format("采样时间 %s",lowStrainDataDbs.get(i).sampleTime));
            if (lowStrainDataDbs.get(i).isValid==0)
            {
                waveViewHodler.tvIsVaild.setTextColor(ContextCompat.getColor(context,R.color.colorPrimary));
                waveViewHodler.tvIsVaild.setText("有效");
            }
            else
            {
                waveViewHodler.tvIsVaild.setText("无效");
                waveViewHodler.tvIsVaild.setTextColor(Color.RED);
            }

            if (checkable)
                waveViewHodler.checkBox.setVisibility(View.VISIBLE);
            else
                waveViewHodler.checkBox.setVisibility(View.GONE);

            if (chckeLink.get(i))
            {
                waveViewHodler.checkBox.setChecked(true);
            }
            else
            {
                waveViewHodler.checkBox.setChecked(false);
            }

            waveViewHodler.checkBox.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v)
                {
                    if (checkable)
                    {
                        if (waveViewHodler.checkBox.isChecked())
                        {
                            waveViewHodler.checkBox.setChecked(false);
                            chckeLink.put(i,false);

                        }
                        else
                        {
                            waveViewHodler.checkBox.setChecked(true);
                            chckeLink.put(i,true);
                        }
                    }

                }
            });

            waveViewHodler.itemViews.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v)
                {
                    if (checkable)
                    {
                        if (waveViewHodler.checkBox.isChecked())
                        {
                            waveViewHodler.checkBox.setChecked(false);
                            chckeLink.put(i,false);
                        }
                        else
                        {
                            waveViewHodler.checkBox.setChecked(true);
                            chckeLink.put(i,true);
                        }
                    }
                    // 跳转 曲线页面
                }
            });

            waveViewHodler.tvIsVaild.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v)
                {
                    if (checkable)
                        return;
                    PopupMenu popupMenu = new PopupMenu(getActivity(),waveViewHodler.tvIsVaild);
                    popupMenu.getMenuInflater().inflate(R.menu.context_menu,popupMenu.getMenu());
                    if (lowStrainDataDbs.get(i).isValid==0)
                    {
                        popupMenu.getMenu().findItem(R.id.Choose_Valid).setTitle("标记为无效");
                    }
                    else
                    {
                        popupMenu.getMenu().findItem(R.id.Choose_Valid).setTitle("标记为有效");

                    }
                    popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener()
                    {
                        @Override
                        public boolean onMenuItemClick(MenuItem item)
                        {
                            switch (item.getItemId())
                            {
                                case R.id.Choose_Valid:
                                    if (mLowStrainDatas.get(i).isValid==0)
                                    {
                                        DbCenter.makeAsIsValid(mLowStrainDatas.get(i).uuid,1);
                                        mLowStrainDatas.get(i).isValid = 1;
                                        notifyDataChanged();
                                    }
                                    else
                                    {
                                        DbCenter.makeAsIsValid(mLowStrainDatas.get(i).uuid,0);
                                        mLowStrainDatas.get(i).isValid = 0;
                                        notifyDataChanged();
                                    }
                                    break;
                            }
                            return false;
                        }
                    });
                    popupMenu.show();
                }
            });

           waveViewHodler.itemViews.setOnLongClickListener(new View.OnLongClickListener()
            {
                @Override
                public boolean onLongClick(View v)
                {
                    if (checkable)
                        return false;
                    else
                    {
                        multipleLayout.setVisibility(View.VISIBLE);
                        setIsCheckedMode(true);
                    }
                    return true;
                }
            });
        }
        @Override
        public int getItemCount()
        {
            return lowStrainDataDbs.size();
        }


        public void setIsCheckedMode(boolean checkacble)
        {
            unCheckedAll();
            this.checkable = checkacble;
            notifyDataChanged();
        }

        private void checkedAll()
        {
            for (int i = 0; i < chckeLink.size(); i++) {
                chckeLink.put(i,true);
            }
            notifyDataChanged();
        }

        private void unCheckedAll()
        {
            for (int i = 0; i < chckeLink.size(); i++) {
                chckeLink.put(i,false);
            }
            notifyDataChanged();
        }


        private void makeValidFlag(boolean isValid)
        {
            for (int i = 0; i < chckeLink.size(); i++)
            {
                if (chckeLink.get(i))
                {
                    if (!isValid)
                    {
                        mLowStrainDatas.get(i).isValid = 1;
                        DbCenter.makeAsIsValid(mLowStrainDatas.get(i).uuid,1);
                    }
                    else
                    {
                        mLowStrainDatas.get(i).isValid = 0;
                        DbCenter.makeAsIsValid(mLowStrainDatas.get(i).uuid,0);
                    }
                }
            }
            notifyDataChanged();
            UiUtils.showToast("操作成功");

        }




    }
    private class WaveViewHodler extends RecyclerView.ViewHolder
    {
        public TextView tvSerilaNo,tvInfo,tvIsVaild;
        public View itemViews;
        private CheckBox checkBox;
        public WaveViewHodler(View itemView) {
            super(itemView);
            tvSerilaNo = (TextView) itemView.findViewById(R.id.SerilaNo);
            tvInfo = (TextView) itemView.findViewById(R.id.Info);
            tvIsVaild = (TextView) itemView.findViewById(R.id.Isvalid);
            itemViews = itemView.findViewById(R.id.ItemView);
            checkBox = (CheckBox) itemView.findViewById(R.id.Checkbox);

        }
    }

    @Override
    public void onDestroyView()
    {
        super.onDestroyView();
        if (!EventBus.getDefault().isRegistered(this))
        {
            EventBus.getDefault().unregister(this);
        }
    }


}
